// pages/classHomePage/debate/index/index.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    all_debate_list: [],
    all_activity_list: null,
    people: null,
    groupList: null,
    choose_group_id: null,
    card: [{
      img: {
        url: "/static/images/news/avatar_1.jpg"
      },
      title: {
        text: "辩论会"
      },
      tag: {
        text: "1小时前"
      },
      header: {
        bgcolor: "#F7F7F7",
        line: true
      }
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this
    _this.setData({
      people: wx.getStorageSync('people')
    })
    _this.get_all_debate()
    _this.get_all_group_task()
  },

  get_all_group_task: function () {
    let _this = this
    let teacher_id = null
    let course_name = null
    if (wx.getStorageSync("people") == 'teacher') {
      teacher_id = app.globalData.teacher_info['id']
      course_name = app.globalData.banji_info['courseName']
    } else if (wx.getStorageSync("people") == 'student') {
      teacher_id = app.globalData.banji_info['teacher_id']
      course_name = app.globalData.banji_info['className']
    }

    return new Promise(function (resolve, reject) {
      let data = {
        'teacher_id': teacher_id,
        'course_name': course_name
      }
      app.formPost('/get_all_group_task', data).then(res => {
        console.log('/get_all_group_task 获取老师所有的分组任务：', res);
        for (let index = 0; index < res.length; index++) {
          res[index]['text'] = res[index]['groupType']
        }
        _this.setData({
          groupList: res
        })
        // resolve(res)
      })
    })
  },

  get_group: function (e) {
    let _this = this
    console.log('取分组id', _this.data.groupList[e.detail['id']]['groupId']);
    _this.setData({
      choose_group_id: _this.data.groupList[e.detail['id']]['groupId']
    })
  },

//查询辩论会报错的函数：
teacher_add_debate: function () {
  let _this = this
  wx.showModal({
    title: '创建辩论会',
    editable: true, // 显示输入框
    placeholderText: '输入辩论会主题', // 显示输入框提示信息
    success: res => {
      if (res.confirm) { // 点击了确认
        let debateTopic = res.content
        if (!debateTopic) {
          wx.showToast({
            title: '请输入辩论主题',
            icon: 'none'
          });
          return;
        }

        if (!_this.data.choose_group_id) {
          wx.showToast({
            title: '请先选择分组',
            icon: 'none'
          });
          return;
        }

        let data = {
          'course_name': app.globalData.banji_info['courseName'],
          'teacher_id': app.globalData.teacher_info['id']
        }
        app.formPost('/add_activity_debate', data).then(res => {
          console.log('创建辩论会结果：', res);
          let id = res['id']
          _this.get_all_activity().then(res => {
            for (let index = 0; index < res.length; index++) {
              if (id == res[index]['activity_id']) {
                let activity_id = res[index]['activity_id']
                let teacher_id = res[index]['teacher_id']
                if (!activity_id || !teacher_id) {
                  wx.showToast({
                    title: '活动或教师信息缺失',
                    icon: 'none'
                  });
                  return;
                }

                let data_add_debate = {
                  'activity_id': activity_id,
                  'course_name': app.globalData.banji_info['courseName'],
                  'debateTopic': debateTopic,
                  'group_id': _this.data.choose_group_id,
                  'teacher_id': teacher_id
                }
                console.log('data_add_debate:', data_add_debate);

                app.formPost('/add_debate', data_add_debate).then(res => {
                  console.log('创建activity的debate /add_debate结果：', res);
                  _this.get_all_debate()
                  _this.onLoad()
                }).catch(err => {
                  console.error('创建辩论会失败', err);
                  wx.showToast({
                    title: '创建辩论会失败，请检查数据',
                    icon: 'none'
                  });
                });
              }
            }
          })
        }).catch(err => {
          console.error('创建辩论会失败', err);
        });
      }
    }
  })
},

  /*teacher_add_debate: function () {
    let _this = this
    wx.showModal({
      title: '创建辩论会',
      editable: true, //显示输入框
      placeholderText: '输入辩论会主题', //显示输入框提示信息
      success: res => {
        if (res.confirm) { //点击了确认
          console.log(res.content) //用户输入的值
          let debateTopic = res.content
          let data = {
            'course_name': app.globalData.banji_info['courseName'],
            'teacher_id': app.globalData.teacher_info['id']
          }
          app.formPost('/add_activity_debate', data).then(res => {
            console.log('创建辩论会结果：', res);
            let id = res['id']
            _this.get_all_activity().then(res => {
              for (let index = 0; index < res.length; index++) {
                if (id == res[index]['activity_id']) {
                  let activity_id = res[index]['activity_id']
                  let data_add_debate = {
                    'activity_id': activity_id,
                    'course_name': app.globalData.banji_info['courseName'],
                    'debateTopic': debateTopic,
                    'group_id': _this.data.choose_group_id, //改！！！！！！！
                    'teacher_id': res[index]['teacher_id']
                  }
                  app.formPost('/add_debate', data_add_debate).then(res => {
                    console.log('创建activity的debate /add_debate结果：', res);
                    _this.get_all_debate()
                    _this.onLoad()
                  })
                }
              }
            })

          }).catch(err => {
            console.error('创建辩论会失败', err);
          });     //添加错误逻辑
        }
      }
    })
  },*/

  get_all_debate: function () {
    let _this = this
    return new Promise(function (resolve, reject) {
      let data = {}
      if (wx.getStorageSync("people") == 'student') {
        data = {
          'course_name': app.globalData.banji_info['className']
        }
      } else if (wx.getStorageSync("people") == 'teacher') {
        data = {
          'course_name': app.globalData.banji_info['courseName']
        }
      }
      app.formPost('/get_all_debate', data).then(res => {
        console.log('查询辩论会结果/get_all_debate：', res);
        _this.setData({
          all_debate_list: res
        })
        resolve(res)
      })
    })
  },

  get_all_activity: function () {
    let _this = this
    return new Promise(function (resolve, reject) {
      let data = {}
      if (wx.getStorageSync("people") == 'student') {
        data = {
          'course_name': app.globalData.banji_info['className'],
          'teacher_id': app.globalData.banji_info['teacher_id']
        }
      } else if (wx.getStorageSync("people") == 'teacher') {
        data = {
          'course_name': app.globalData.banji_info['courseName'],
          'teacher_id': app.globalData.banji_info['teacherId']
        }
      }
      app.formPost('/get_all_activity', data).then(res => {
        console.log('查询activity活动结果/get_all_activity：', res);
        _this.setData({
          all_activity_list: res
        })
        resolve(res)
      })
    })
  },

  gotoDebateMessage: function (e) {
    console.log(e.currentTarget.dataset['debateid']);
    wx.navigateTo({
      url: '/pages/classHomePage/debate/debateMessage/debateMessage?debateid=' + String(e.currentTarget.dataset['debateid']) + '&type=' + String(e.currentTarget.dataset['debate_type']),
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})